package cn.slipi.admin.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author litao
 */
public class ServletUtil {
    /**
     * 获取 Body 参数
     *
     * @param request
     */
    public static SortedMap<String, Object> getBodyParams(final HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String str;
        StringBuilder wholeStr = new StringBuilder();
        //一行一行的读取body体里面的内容；
        while ((str = reader.readLine()) != null) {
            wholeStr.append(str);
        }
        if (StringUtils.isEmpty(wholeStr)) {
            wholeStr.append("{}");
        }
        //转化成json对象
        SortedMap<String, Object> firstSort = JSONObject.parseObject(wholeStr.toString(), SortedMap.class);
        return objectSort(firstSort);
    }

    private static SortedMap<String, Object> objectSort(SortedMap<String, Object> info) {
        info.forEach((key, value) -> {
            if (value instanceof JSONObject) {
                String jsonStr = JSONObject.toJSONString(value);
                SortedMap<String, Object> sortObject = JSONObject.parseObject(jsonStr, SortedMap.class);
                objectSort(sortObject);
            } else if (value instanceof JSONArray) {
                JSONArray newArr = new JSONArray();
                ((JSONArray) value).forEach(single -> {
                    if (single instanceof JSONObject) {
                        SortedMap<String, Object> sortObject = JSONObject.parseObject(single.toString(), SortedMap.class);
                        newArr.add(objectSort(sortObject));
                    } else {
                        newArr.add(single.toString());
                    }
                });
                info.put(key, newArr);
            }
        });
        return info;
    }

    /**
     * 将URL请求参数转换成Map
     *
     * @param request
     */
    public static SortedMap<String, Object> getUrlParams(HttpServletRequest request) {
        String param = "";
        SortedMap<String, Object> result = new TreeMap<>();
        if (StringUtils.isEmpty(request.getQueryString())) {
            return result;
        }

        try {
            param = URLDecoder.decode(request.getQueryString(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String[] params = param.split("&");
        for (String s : params) {
            int index = s.indexOf("=");
            result.put(s.substring(0, index), s.substring(index + 1));
        }
        return result;
    }

    public static SortedMap<String, Object> getAllParams(HttpServletRequest request) throws IOException {

        SortedMap<String, Object> result = new TreeMap<>();
        //获取URL上的参数
        Map<String, Object> urlParams = getUrlParams(request);
        urlParams.forEach((key, value) -> {
            result.put(key, value.toString());
        });
        Map<String, Object> bodyParams = new HashMap<>(16);
        // get请求不需要拿body参数
        if (!(HttpMethod.GET.name().equals(request.getMethod()) || HttpMethod.DELETE.name().equals(request.getMethod()))) {
            bodyParams = getBodyParams(request);
        }
        //将URL的参数和body参数进行合并
        bodyParams.forEach((key, value) -> {
            if (!(value instanceof JSONArray || value instanceof JSONObject)) {
                result.put(key, value.toString());
            } else {
                result.put(key, value);
            }
        });
        return result;
    }
}
